package com.dabai.qrtools.other;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Icon;
import android.os.Build;

import androidx.fragment.app.FragmentActivity;

import com.dabai.qrtools.R;
import com.dabai.qrtools.ui.FreeCopyActivity;
import com.dabai.qrtools.ui.GenerateActivity;
import com.dabai.qrtools.ui.ResultActivity;
import com.dabai.qrtools.utils.DabaiUtils;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.permissionx.guolindev.PermissionX;

import java.util.ArrayList;
import java.util.Collections;

/**
 * Description : 主页的工具类
 *
 * @author BAI
 */
public class MainUtils {



    /**
     * 得到执行的方式
     *
     * @param context 上下文
     * @return int
     */
    public static String getErrorCorrectionLevel(Context context) {
        switch (DabaiUtils.getSettingSharedPreferences(context).getString("errorCorrectionLevel"
                , "30")) {
            case "7":
                return "L";
            case "15":
                return "M";
            case "25":
                return "Q";
            case "30":
                return "H";
        }
        return "H";
    }


    /**
     * 得到qr的版本
     * 得到执行的方式
     *
     * @param context 上下文
     * @return int
     */
    public static int getQrVersion(Context context) {
        return DabaiUtils.getSettingSharedPreferences(context).getInt("version"
                , 0);
    }

    public static void permissionToApplyFor(FragmentActivity fragmentActivity){

        //兼容Android Q
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {

            PermissionX.init(fragmentActivity)
                    .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .request((allGranted, grantedList, deniedList) -> {
                        if (!allGranted) {
                            DabaiUtils.showToast(fragmentActivity, "部分功能需要储存权限");
                        }
                    });
        }

    }



    @SuppressLint("UnspecifiedImmutableFlag")
    public static void addShortCut(Context context, String name, int icon, Intent intent) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            ShortcutManager shortcutManager = (ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE);
            if (shortcutManager.isRequestPinShortcutSupported()) {
                intent.setAction(Intent.ACTION_VIEW); //action必须设置，不然报错
                ShortcutInfo info;
                info = new ShortcutInfo.Builder(
                        context,
                        "The only id" + (int) (Math.random() * 10000)
                )
                        .setIcon(Icon.createWithResource(context, icon))
                        .setShortLabel(name)
                        .setIntent(intent)
                        .build();

                //当添加快捷方式的确认弹框弹出来时，将被回调
                PendingIntent shortcutCallbackIntent =
                        PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                shortcutManager.requestPinShortcut(info, shortcutCallbackIntent.getIntentSender());
            }
        }else {
            DabaiUtils.showToast(context,"当前系统不支持快捷方式!");
        }
    }



    @SuppressLint("Range")
    public static void showGenerateHistory(Context context) {

        //数据库创建与初始化
        SQLiteDatabase db = context.openOrCreateDatabase("HistoricalRecord", Context.MODE_PRIVATE, null);
        String create = "create table if not exists GenerateHistoricalRecord(id integer primary key autoincrement,content text not null unique);";
        db.execSQL(create);


        ArrayList<String> arrayList = new ArrayList<>();
        ArrayList<String> arrayList2 = new ArrayList<>();

        String search = "select * from GenerateHistoricalRecord";
        Cursor cursor = db.rawQuery(search, null);

        while (cursor.moveToNext()) {
            String text = cursor.getString(cursor.getColumnIndex("content"));
            arrayList.add(text);
            arrayList2.add(text.length()>20?text.substring(0,20)+"...":text);
        }
        cursor.close();

        if (arrayList.isEmpty()) {
            return;
        }


        Collections.reverse(arrayList);
        Collections.reverse(arrayList2);

        String[] items = arrayList.toArray(new String[0]);
        String[] items2 = arrayList2.toArray(new String[0]);

        new MaterialAlertDialogBuilder(context)
                .setTitle("生成记录")
                .setItems(items2, (dialog, which) -> {
                    toGenerateQr(context, items[which]);
                })
                .setPositiveButton("确认", null)
                .setNeutralButton("清空", (dialog, which) -> {
                    delTable(db, "GenerateHistoricalRecord");
                    DabaiUtils.showToast(context, "已清空");
                })
                .show().getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);

    }

    @SuppressLint("Range")
    public static void showScanHistory(Context context) {

        //数据库创建与初始化
        SQLiteDatabase db = context.openOrCreateDatabase("HistoricalRecord", Context.MODE_PRIVATE, null);
        String create = "create table if not exists ScanHistory(id integer primary key autoincrement,content text not null unique);";
        db.execSQL(create);


        ArrayList<String> arrayList = new ArrayList<>();
        ArrayList<String> arrayList2 = new ArrayList<>();

        String search = "select * from ScanHistory";
        Cursor cursor = db.rawQuery(search, null);

        while (cursor.moveToNext()) {
            String text = cursor.getString(cursor.getColumnIndex("content"));
            arrayList.add(text);
            arrayList2.add(text.length()>20?text.substring(0,20)+"...":text);
        }
        cursor.close();

        if (arrayList.isEmpty()) {
            return;
        }


        Collections.reverse(arrayList);
        Collections.reverse(arrayList2);

        String[] items = arrayList.toArray(new String[0]);
        String[] items2 = arrayList2.toArray(new String[0]);


        new MaterialAlertDialogBuilder(context)
                .setTitle("扫描记录")
                .setItems(items2, (dialog, which) -> {
                    toScanQr(context, items[which]);
                })
                .setPositiveButton("确认", null)
                .setNeutralButton("清空", (dialog, which) -> {
                    delTable(db, "ScanHistory");
                    DabaiUtils.showToast(context, "已清空");
                })
                .show().getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);

    }



    public static void delTable(SQLiteDatabase db, String tableName) {
        String sql = "delete from " + tableName;
        String sql2 = "update sqlite_sequence SET seq =0 where name ='" + tableName + "'";//自增长ID为0

        db.execSQL(sql2);
        db.execSQL(sql);
    }

    public static void toGenerateQr(Context context, String text) {
        Intent intent = new Intent(context, GenerateActivity.class);
        intent.putExtra("incomingText", text);
        context.startActivity(intent);
    }

    public static void toScanQr(Context context, String text) {
        Intent intent = new Intent(context, ResultActivity.class);
        intent.putExtra("result", text);
        context.startActivity(intent);
    }

    public static void toFreeCopy(Context context, String text) {
        Intent intent = new Intent(context, FreeCopyActivity.class);
        intent.putExtra("content", text);
        context.startActivity(intent);
    }


}
